package org.springblade.modules.restaurant.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.CommodityCollect;
import org.springblade.modules.restaurant.service.ICommodityCollectService;
import org.springblade.modules.restaurant.vo.PurchaseCommodityTreeVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户采购商品收藏表
 *
 * @author harry
 * @公众号 Harry技术
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/restaurant/commoditycollect")
@Tag(name = "API - 用户采购商品收藏")
public class ApiCommodityCollectController {

	private ICommodityCollectService commodityCollectService;


	@GetMapping("/list")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "用户收藏列表")
	public R<List<PurchaseCommodityTreeVO>> list() {
		Long userId = SecureUtil.getUserId();
		List<PurchaseCommodityTreeVO> list = commodityCollectService.selectPurchaseCommodityList(userId);
		return R.data(list);
	}
	/**
	 * 收藏 取消收藏
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "收藏 取消收藏", description = "商品ID")
	public R save(Long commodityId) {

		Long userId = SecureUtil.getUserId();

		CommodityCollect commodityCollect = commodityCollectService.getOne(Wrappers.<CommodityCollect>lambdaQuery()
			.eq(CommodityCollect::getUserId, userId)
			.eq(CommodityCollect::getCommodityId, commodityId));

		boolean res;
		// 如果已经收藏，则取消收藏
		if (Func.isNotEmpty(commodityCollect)) {
			res = commodityCollectService.removeById(commodityCollect);
		} else {
			// 如果没有收藏，则收藏
			CommodityCollect newCommodityCollect = new CommodityCollect();
			newCommodityCollect.setCommodityId(commodityId);
			newCommodityCollect.setUserId(userId);
			res = commodityCollectService.save(newCommodityCollect);
		}
		return R.status(res);
	}
}
